package caiwei.android_study_sample.utility;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;
import android.util.Log;

public final class HTTPUtils {
	private HTTPUtils() {
	}

	
	public static synchronized String getRequest(String url1) {
		try {			
			URL url = new URL(url1);
			URLConnection con = url.openConnection();
			con.setConnectTimeout(5000);			
			if (HttpURLConnection.HTTP_OK != ((HttpURLConnection) con)
					.getResponseCode()) {
				Log.i("HTTPUtils", "connection failed");
				
				return "failed";
			}else{
				String result = "http status code: "
						+ ((HttpURLConnection) con).getResponseCode() + "\n";
				InputStream is = con.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(is);
				ByteArrayBuffer bab = new ByteArrayBuffer(32);
				int current = 0;
				while ((current = bis.read()) != -1) {
					bab.append((byte) current);
				}

				result = EncodingUtils.getString(bab.toByteArray(), HTTP.UTF_8);
				bis.close();
				is.close();

				return result;
			}
			
		} catch (Exception e) {
			Log.e("HTTPUtils", "connection exception");
			return "failed";
		}
	}
}
